import json
import random
from django.shortcuts import render, HttpResponse
from myapp.utils.Bootstrap import BootstrapModelForm
from django.views.decorators.csrf import csrf_exempt
from myapp import models
from datetime import datetime
from myapp.utils.Pagination import Pagination


class orderModelForm(BootstrapModelForm):
    class Meta:
        model = models.Order
        # fields = '__all__'
        exclude = ['oid', 'admin']


def order_list(request):
    form = orderModelForm
    query_set = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, query_set=query_set, page_size=5)  # 实例化一个分页类
    context = {  # 用字典放给模板的各个数据
        'form': form,
        'data_set': page_object.data_queryset,  # 分完页的数据
        'page_str': page_object.html(),  # 页码
    }
    return render(request, 'oder_list.html', context)


@csrf_exempt
def order_add(request):
    """新建订单ajax请求"""
    form = orderModelForm(data=request.POST)
    if form.is_valid():
        # 用时间加随机数生成订单号为form.instance.oid赋值
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        # 订单用户用当前登陆人id
        form.instance.admin_id = request.session['info'].get('id')
        form.save()
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))
    data_dict = {'status': False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict))


@csrf_exempt
def order_delete(request):
    """删除订单"""
    nid = request.GET.get("nid")
    exists = models.Order.objects.filter(id=nid).exists()
    if exists:
        models.Order.objects.filter(id=nid).delete()
        data_dict = {
            "status": True
        }
        return HttpResponse(json.dumps(data_dict))
    data_dict = {
        "status": False,
        "error": "需删除的数据不存在，删除失败"
    }
    return HttpResponse(json.dumps(data_dict))


@csrf_exempt
def order_data(request): #此函数用于查询返回给前端需更新的原数据用以前端展示
    uid = request.GET.get("uid")
    print(uid)
    row_obj = models.Order.objects.filter(id=uid).first()
    if row_obj:
        data_dict = {"status": True,
                     "data": {
                         "title": row_obj.title,
                         "price": row_obj.price,
                         "status": row_obj.status
                     }}
        return HttpResponse(json.dumps(data_dict))
    return HttpResponse(json.dumps({"status": False,"error":"需更新的数据不存在"}))

@csrf_exempt
def order_update(request,uid):  # 此方法为对数据执行更新操作
    row_obj = models.Order.objects.filter(id=uid).first()
    form = orderModelForm(data=request.POST, instance=row_obj)
    print(request.POST)
    if row_obj:
        if form.is_valid():
          form.save()
          return HttpResponse(json.dumps({"status": True}))
        return HttpResponse(json.dumps({"status": False,"error":form.errors}))
    return HttpResponse(json.dumps({"status": False, "tips": "需更新的数据不存在，请刷新后重试"}))